from fastapi import APIRouter, HTTPException
from typing import Dict, Any
from datetime import datetime
from app.services import service_manager
from app.schemas.simulation import (
    FaceRecognitionEvent,
    CardSwipeEvent,
    DoorStateEvent,
    AlarmEvent
)

router = APIRouter()

@router.post("/face-recognition")
async def simulate_face_recognition(event: FaceRecognitionEvent):
    """
    模拟海康平台人脸识别事件
    
    示例请求:
    {
        "door_id": "door_001",
        "time": "2024-02-11T10:30:00",
        "person_id": "person_001",
        "name": "张三",
        "confidence": 0.98,
        "capture_image": "base64_image_data"
    }
    """
    try:
        await service_manager.process_face_event(event.dict())
        return {"message": "人脸识别事件已处理", "status": "success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/card-swipe")
async def simulate_card_swipe(event: CardSwipeEvent):
    """
    模拟大华平台刷卡事件
    
    示例请求:
    {
        "door_id": "door_001",
        "time": "2024-02-11T10:30:15",
        "card_no": "card_001",
        "holder_id": "person_001",
        "holder_name": "张三",
        "event_type": "valid_card"
    }
    """
    try:
        await service_manager.process_card_event(event.dict())
        return {"message": "刷卡事件已处理", "status": "success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/door-state")
async def simulate_door_state(event: DoorStateEvent):
    """
    模拟门禁状态变化事件
    
    示例请求:
    {
        "door_id": "door_001",
        "state": "open",  # 或 "closed"
        "time": "2024-02-11T10:30:30"
    }
    """
    try:
        if event.state == "open":
            await service_manager.door_service.open_door(event.door_id)
        else:
            await service_manager.door_service.close_door(event.door_id)
        return {"message": f"门禁状态已更新为: {event.state}", "status": "success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/alarm")
async def simulate_alarm(event: AlarmEvent):
    """
    模拟报警事件
    
    示例请求:
    {
        "door_id": "door_001",
        "alarm_type": "timeout",  # 或 "force_open"
        "description": "门禁超时未关闭"
    }
    """
    try:
        if event.alarm_type == "timeout":
            await service_manager.alarm_service.trigger_timeout_alarm(event.door_id)
        elif event.alarm_type == "force_open":
            await service_manager.alarm_service.trigger_force_open_alarm(event.door_id)
        return {"message": "报警事件已触发", "status": "success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/status/{door_id}")
async def get_door_status(door_id: str):
    """
    获取门禁当前状态
    """
    try:
        state = service_manager.door_service.door_status.get(door_id)
        alarms = service_manager.alarm_service.get_alarm_history(door_id)
        return {
            "door_id": door_id,
            "current_state": state,
            "active_alarms": [alarm for alarm in alarms if alarm["status"] == "active"],
            "alarm_history": alarms
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 